package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"strings"
	"wph/models"
)

type OrderController struct {
	beego.Controller
}
type JsonData struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *OrderController) Add() {
	Name := c.GetString("name")
	price, _ := c.GetFloat("price", 64)
	img := c.GetString("img")
	intro := c.GetString("intro")
	order := models.Order{
		Name:  Name,
		Price: price,
		Img:   img,
		Intro: intro,
	}
	err := models.DB.Create(&order).Error
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *OrderController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "文件过大",
			Data: nil,
		}
		c.ServeJSON()
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	suffixMap := map[string]bool{
		".png": true,
		".jpg": true,
	}
	if !suffixMap[suffix] {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "格式错误，只能是.png.jpg",
			Data: nil,
		}
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		ImgSrc := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "上传成功",
			Data: ImgSrc,
		}
		c.ServeJSON()
	}
}
func (c *OrderController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 5)
	orders, total, err := models.OrderList(page, pageSize)
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "分页查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		SrcData := make(map[string]interface{})
		SrcData["orders"] = orders
		SrcData["total"] = total
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "分页查询成功",
			Data: SrcData,
		}
		c.ServeJSON()
	}
}
